package com.cardone.platform.configuration.controller;

import java.util.List;
import java.util.Map;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.cardone.common.dto.PaginationDto;
import com.cardone.context.Constants;
import com.cardone.platform.configuration.dto.DictionaryDto;
import com.cardone.platform.configuration.dto.DictionaryTypeDto;
import com.cardone.platform.configuration.service.ConfigurationService;
import com.cardone.platform.configuration.validator.DictionaryTypeValidator;
import com.cardone.platform.configuration.validator.DictionaryValidator;
import com.cardone.platform.configuration.vo.DictionaryVo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 字典
 * 
 * @author yaoht
 */
@Setter
@Slf4j
@RequestMapping(DictionaryController.Paths.ROOT)
@Controller
public class DictionaryController {
	/**
	 * models集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum models {
		/**
		 * 字典
		 */
		dictionary,

		/**
		 * 字典类型
		 */
		dictionaryType,

		/**
		 * 消息
		 */
		message;
	}

	/**
	 * 路径集合
	 * 
	 * @author yaoht
	 * 
	 */
	public enum Paths {
		/**
		 * 字典类型编辑视图路径
		 */
		DICTIONARY_TYPEEdit("dictionaryType/edit"),

		/**
		 * 字典类型主界面视图路径
		 */
		DICTIONARY_TYPEIndex("dictionaryType/index"),

		/**
		 * 字典类型编辑视图路径
		 */
		DICTIONARY_TYPENew("dictionaryType/new"),

		/**
		 * 字典类型查看编辑视图路径
		 */
		DICTIONARY_TYPEView("dictionaryType/view"),

		/**
		 * 字典编辑视图路径
		 */
		DICTIONARYEdit("dictionary/edit"),

		/**
		 * 字典主界面视图路径
		 */
		DICTIONARYIndex("dictionary/index"),

		/**
		 * 字典编辑视图路径
		 */
		DICTIONARYNew("dictionary/new"),

		/**
		 * 字典查看编辑视图路径
		 */
		DICTIONARYView("dictionary/view"),

		/**
		 * 字典主界面
		 */
		index;

		/**
		 * 字典视图根目录
		 */
		public static final String ROOT = "/platform/configuration/dictionary/";

		/**
		 * 路径
		 */
		private final String path;

		/**
		 * 构建
		 * 
		 */
		private Paths() {
			this.path = Paths.ROOT + this.name();
		}

		/**
		 * 构建
		 * 
		 * @param path
		 *            路径
		 */
		private Paths(final String path) {
			this.path = Paths.ROOT + path;
		}

		/**
		 * 获取
		 * 
		 * @return 路径
		 */
		public String path() {
			return this.path;
		}
	}

	/**
	 * 字典服务
	 */
	@Qualifier(ConfigurationService.BEAN_ID)
	@Autowired(required = false)
	private ConfigurationService configurationService;

	/**
	 * 字典类型验证
	 */
	@Qualifier(DictionaryTypeValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator dictionaryTypeValidator;

	/**
	 * 字典验证
	 */
	@Qualifier(DictionaryValidator.BEAN_ID)
	@Autowired(required = false)
	public Validator dictionaryValidator;

	/**
	 * 字典：删除
	 * 
	 * @param dictionaryVo
	 *            字典视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "dictionary/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> dictionaryDelete(final DictionaryVo dictionaryVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.configurationService.getDictionaryService().deleteDictionaryByIds(dictionaryVo.getDictionary());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (DictionaryController.log.isDebugEnabled()) {
				DictionaryController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 字典：编辑
	 * 
	 * @param dictionaryVo
	 *            字典视图对象
	 * @param model
	 *            上下文映射
	 * @return 字典编辑视图路径
	 */
	@RequestMapping(value = { "dictionary/edit.html" }, method = RequestMethod.GET)
	public String dictionaryEdit(final DictionaryVo dictionaryVo, final Model model) {
		final DictionaryDto dictionary = this.configurationService.getDictionaryService().findDictionaryById(
		        dictionaryVo.getDictionary());

		model.addAttribute(DictionaryController.models.dictionary.name(), dictionary);

		return DictionaryController.Paths.DICTIONARYEdit.path();
	}

	/**
	 * 字典：主界面
	 * 
	 * @return 字典主界面视图路径
	 */
	@RequestMapping(value = { "dictionary/index.html" })
	public String dictionaryIndex() {
		return DictionaryController.Paths.DICTIONARYIndex.path();
	}

	/**
	 * 字典：主界面分页查询
	 * 
	 * @param dictionaryVo
	 *            字典视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "dictionary/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> dictionaryIndexPagination(final DictionaryVo dictionaryVo) {
		final PaginationDto<DictionaryDto> dictionaryPagination = this.configurationService.getDictionaryService()
		        .paginationDictionaryByCode(dictionaryVo.getDictionary());

		final Map<String, Object> dictionaryPaginationMap = Maps.newHashMap();

		dictionaryPaginationMap.put(Constants.total.stringValue(), dictionaryPagination.getTotalSize());
		dictionaryPaginationMap.put(Constants.rows.stringValue(), dictionaryPagination.getDataList());

		return dictionaryPaginationMap;
	}

	/**
	 * 字典：新增
	 * 
	 * @param dictionaryVo
	 *            字典视图对象
	 * @param model
	 *            上下文映射
	 * @return 字典编辑视图路径
	 */
	@RequestMapping(value = { "dictionary/new.html" }, method = RequestMethod.GET)
	public String dictionaryNew(final DictionaryVo dictionaryVo, final Model model) {
		model.addAttribute(DictionaryController.models.dictionary.name(), dictionaryVo.getDictionary());

		return DictionaryController.Paths.DICTIONARYNew.path();
	}

	/**
	 * 字典：保存
	 * 
	 * @param dictionaryVo
	 *            字典视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "dictionary/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String dictionarySave(final DictionaryVo dictionaryVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.dictionaryValidator.validate(dictionaryVo.getDictionary(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.configurationService.getDictionaryService().saveDictionaryByIdOrCode(dictionaryVo.getDictionary());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (DictionaryController.log.isDebugEnabled()) {
				DictionaryController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 字典类型：删除
	 * 
	 * @param dictionaryVo
	 *            字典类型视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "dictionaryType/delete.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> dictionaryTypeDelete(final DictionaryVo dictionaryVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.configurationService.getDictionaryService().deleteDictionaryTypeByIds(dictionaryVo.getDictionaryType());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (DictionaryController.log.isDebugEnabled()) {
				DictionaryController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 字典类型：编辑
	 * 
	 * @param dictionaryVo
	 *            字典类型视图对象
	 * @param model
	 *            上下文映射
	 * @return 字典类型编辑视图路径
	 */
	@RequestMapping(value = { "dictionaryType/edit.html" }, method = RequestMethod.GET)
	public String dictionaryTypeEdit(final DictionaryVo dictionaryVo, final Model model) {
		final DictionaryTypeDto dictionaryType = this.configurationService.getDictionaryService().findDictionaryTypeById(
		        dictionaryVo.getDictionaryType());

		model.addAttribute(DictionaryController.models.dictionaryType.name(), dictionaryType);

		return DictionaryController.Paths.DICTIONARY_TYPEEdit.path();
	}

	/**
	 * 字典类型：主界面
	 * 
	 * @return 字典类型主界面视图路径
	 */
	@RequestMapping(value = { "dictionaryType/index.html" })
	public String dictionaryTypeIndex() {
		return DictionaryController.Paths.DICTIONARY_TYPEIndex.path();
	}

	/**
	 * 字典类型：主界面分页查询
	 * 
	 * @param dictionaryVo
	 *            字典类型视图对象
	 * @return 分页数据，json格式
	 */
	@RequestMapping(value = { "dictionaryType/index/pagination.json" })
	@ResponseBody
	public Map<String, Object> dictionaryTypeIndexPagination(final DictionaryVo dictionaryVo) {
		final PaginationDto<DictionaryTypeDto> dictionaryTypePagination = this.configurationService.getDictionaryService()
		        .paginationDictionaryTypeByCode(dictionaryVo.getDictionaryType());

		final Map<String, Object> dictionaryTypePaginationMap = Maps.newHashMap();

		dictionaryTypePaginationMap.put(Constants.total.stringValue(), dictionaryTypePagination.getTotalSize());
		dictionaryTypePaginationMap.put(Constants.rows.stringValue(), dictionaryTypePagination.getDataList());

		return dictionaryTypePaginationMap;
	}

	/**
	 * 字典类型：新增
	 * 
	 * @param dictionaryVo
	 *            字典类型视图对象
	 * @param model
	 *            上下文映射
	 * @return 字典类型编辑视图路径
	 */
	@RequestMapping(value = { "dictionaryType/new.html" }, method = RequestMethod.GET)
	public String dictionaryTypeNew(final DictionaryVo dictionaryVo, final Model model) {
		model.addAttribute(DictionaryController.models.dictionaryType.name(), dictionaryVo.getDictionaryType());

		return DictionaryController.Paths.DICTIONARY_TYPENew.path();
	}

	/**
	 * 字典类型：保存
	 * 
	 * @param dictionaryVo
	 *            字典类型视图对象
	 * @param bindingResult
	 *            绑定对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "dictionaryType/save.txt" }, method = RequestMethod.POST)
	@ResponseBody
	public String dictionaryTypeSave(final DictionaryVo dictionaryVo, BindingResult bindingResult) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.dictionaryTypeValidator.validate(dictionaryVo.getDictionaryType(), bindingResult);

			if (bindingResult.hasErrors()) {
				List<String> messageList = Lists.newArrayList();

				for (final ObjectError objectError : bindingResult.getAllErrors()) {
					messageList.add(objectError.getDefaultMessage());
				}

				String message = StringUtils.join(messageList, org.apache.commons.lang3.StringUtils.EMPTY);

				throw new Exception(message);
			}

			this.configurationService.getDictionaryService().saveDictionaryTypeByIdOrCode(dictionaryVo.getDictionaryType());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (DictionaryController.log.isDebugEnabled()) {
				DictionaryController.log.debug(e.getMessage(), e);
			}
		}

		return JSON.toJSONString(jsonMap);
	}

	/**
	 * 字典类型：更新
	 * 
	 * @param dictionaryVo
	 *            字典类型视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "dictionaryType/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> dictionaryTypeUpdate(final DictionaryVo dictionaryVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.configurationService.getDictionaryService().updateDictionaryTypeByIds(dictionaryVo.getDictionaryType());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (DictionaryController.log.isDebugEnabled()) {
				DictionaryController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 字典类型：验证
	 * 
	 * @param dictionaryVo
	 *            字典类型视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "dictionaryType/validationByCode.json" })
	@ResponseBody
	public Boolean dictionaryTypeValidationByCode(final DictionaryVo dictionaryVo) {
		try {
			final int count = this.configurationService.getDictionaryService().readDictionaryTypeByCodeNqId(
			        dictionaryVo.getDictionaryType());

			return (count < 1);
		} catch (final Exception e) {
			if (DictionaryController.log.isDebugEnabled()) {
				DictionaryController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 字典类型：查看
	 * 
	 * @param dictionaryVo
	 *            字典类型视图对象
	 * @param model
	 *            上下文映射
	 * @return 字典类型查看编辑视图路径
	 */
	@RequestMapping(value = { "dictionaryType/view.html" }, method = RequestMethod.GET)
	public String dictionaryTypeView(final DictionaryVo dictionaryVo, final Model model) {
		final DictionaryTypeDto dictionaryType = this.configurationService.getDictionaryService().findDictionaryTypeById(
		        dictionaryVo.getDictionaryType());

		model.addAttribute(DictionaryController.models.dictionaryType.name(), dictionaryType);

		return DictionaryController.Paths.DICTIONARY_TYPEView.path();
	}

	/**
	 * 字典：更新
	 * 
	 * @param dictionaryVo
	 *            字典视图对象
	 * @return 处理结果，json格式
	 */
	@RequestMapping(value = { "dictionary/update.json" }, method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> dictionaryUpdate(final DictionaryVo dictionaryVo) {
		final Map<String, Object> jsonMap = Maps.newHashMap();

		try {
			this.configurationService.getDictionaryService().updateDictionaryByIds(dictionaryVo.getDictionary());
		} catch (final Exception e) {
			jsonMap.put(Constants.message.stringValue(), e.getMessage());

			if (DictionaryController.log.isDebugEnabled()) {
				DictionaryController.log.debug(e.getMessage(), e);
			}
		}

		return jsonMap;
	}

	/**
	 * 字典：验证
	 * 
	 * @param dictionaryVo
	 *            字典视图对象
	 * @return 验证结果
	 */
	@RequestMapping(value = { "dictionary/validationByCode.json" })
	@ResponseBody
	public Boolean dictionaryValidationByCode(final DictionaryVo dictionaryVo) {
		try {
			final int count = this.configurationService.getDictionaryService().readDictionaryByCodeNqId(dictionaryVo.getDictionary());

			return (count < 1);
		} catch (final Exception e) {
			if (DictionaryController.log.isDebugEnabled()) {
				DictionaryController.log.debug(e.getMessage(), e);
			}
		}

		return false;
	}

	/**
	 * 字典：查看
	 * 
	 * @param dictionaryVo
	 *            字典视图对象
	 * @param model
	 *            上下文映射
	 * @return 字典查看编辑视图路径
	 */
	@RequestMapping(value = { "dictionary/view.html" }, method = RequestMethod.GET)
	public String dictionaryView(final DictionaryVo dictionaryVo, final Model model) {
		final DictionaryDto dictionary = this.configurationService.getDictionaryService().findDictionaryById(
		        dictionaryVo.getDictionary());

		model.addAttribute(DictionaryController.models.dictionary.name(), dictionary);

		return DictionaryController.Paths.DICTIONARYView.path();
	}
}
